package org.example.controller;

import org.example.entity.Approval;
import org.example.entity.CommonResult;
import org.example.entity.Creation;
import org.example.service.ApprovalService;
import org.example.service.CreationService;
import org.springframework.scripting.support.RefreshableScriptTargetSource;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


import javax.annotation.Resource;
import java.util.Map;

@RequestMapping("/approval")
@RestController
public class ApprovalController {

    @Resource
    RestTemplate restTemplate;
    @Resource
    ApprovalService approvalService;


    @Resource
    CreationService creationService;

    @RequestMapping("/like")
    public CommonResult<Approval> giveLike(@RequestBody Approval approval){
        Creation creation = creationService.getCreation(approval.getCreationId());
        CommonResult forObject = restTemplate.getForObject("http://personage/user/addApproval?username=" + creation.getUsername(), CommonResult.class);
        Map res= (Map) forObject.getData();
        /*User user = userService.getUserByName(creation.getUsername());*/
        if(approvalService.addApproval(approval)&&forObject.getCode()==200){
            return new CommonResult<>(200,"success",null);
        }
        return new CommonResult<>(400,"error",null);
    }

    @RequestMapping("/withdraw")
    public CommonResult<Approval> withdrawLike(@RequestBody Approval approval){
        if(approvalService.deleteApproval(approval)){
            return new CommonResult<>(200,"success",null);
        }
        return new CommonResult<>(400,"error",null);
    }

    /**
     * 功能：得到点赞数
     * @param creationId
     * @return 点赞数
     */
    @RequestMapping("/getLikeNum")
    public CommonResult<Integer> getLikeNumber(@RequestParam("creationId") Long creationId){
        if(approvalService.getApprovalNumber(creationId)!=null){
            return new CommonResult<>(200,"success",approvalService.getApprovalNumber(creationId));
        }
        return new CommonResult<>(400,"error",null);
    }
}

